package com.hlcl.huaji.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.elcl.activity.fragment.BaseFragment;
import com.elcl.network.AppContext;
import com.elcl.storage.ApplicationCache;
import com.elcl.support.userage.domain.BaseSimpleItem;
import com.elcl.util.ListUtils;
import com.elcl.util.StringUtils;
import com.elcl.util.UriUtils;
import com.elcl.widget.view.indictor.ExplandanableLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hlcl.huaji.LoginActivity;
import com.hlcl.huaji.R;
import com.hlcl.huaji.ctrl.DialogUtils;
import com.hlcl.huaji.ctrl.MineCtrl;
import com.hlcl.huaji.ctrl.adapter.MineAdapter;
import com.hlcl.huaji.ctrl.adapter.MineOrderAdapter;
import com.hlcl.huaji.ctrl.comp.MyGridView;
import com.hlcl.huaji.ctrl.comp.MyListView;
import com.hlcl.huaji.model.Confing;
import com.hlcl.huaji.model.ConfingResult;
import com.hlcl.huaji.model.LoginResponse;
import com.hlcl.huaji.model.LoginResult;
import com.hlcl.huaji.model.MineLabel;
import com.hlcl.huaji.model.MineLabelResult;
import com.hlcl.huaji.model.OrderNumber;
import com.hlcl.huaji.model.OrderNumberResponse;
import com.hlcl.huaji.server.NetCode;
import com.hlcl.huaji.server.OrderServer;
import com.hlcl.huaji.utils.MyTagView;

import java.util.List;

/**
 * Created by lichunlin on 2018/5/17.
 * 个人中心的界面
 */

public class MineFragment extends BaseFragment {
    private Gson gson = new Gson();
    private MineCtrl mineCtrl = new MineCtrl();

    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.fra_mine, null);

        getConfing();
        initBaseView();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getUserInfoServer();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfoServer();
    }

    private Confing confing;

    private void getConfing() {
        String str_confing = AppContext.getConfing();
        if (StringUtils.isNotBlank(str_confing)) {
            ConfingResult confingResult = gson.fromJson(str_confing, new TypeToken<ConfingResult>() {
            }.getType());
            if (null != confingResult) {
                confing = confingResult.getjData();
            }
        }
    }

    RatingBar rb_comment;
    private MyTagView tag_view;
    private TextView tv_strenth;

    private void initBaseView() {
        rb_comment = view.findViewById(R.id.rb_comment);
        initUserInfoView();
        initOrderView();
        initListView();
        setListener(view, R.id.btn_login_out, new View.OnClickListener() {
            @Override
            public void onClick(View v) {//退出登录
                loginOut();
            }
        });

        tag_view = view.findViewById(R.id.tag_view);
        tv_strenth = view.findViewById(R.id.tv_strenth);
        setListener(view, R.id.tv_strenth, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleExpand();
            }
        });

        initIndicatorView();
    }

    private void getUserInfoServer() {
        OrderServer.getInstance().getUserInfoServer(netHandler);
        OrderServer.getInstance().getMineOrderNumber(netHandler);//获取订单数量
        OrderServer.getInstance().getMineLabel(netHandler);//获取标签数量

    }

    private LoginResponse loginResponse;

    private void initUserInfoView() {
        String userInfo = AppContext.getUerInfo();
        if (StringUtils.isNotBlank(userInfo)) {
            LoginResult loginResult = gson.fromJson(userInfo, new TypeToken<LoginResult>() {
            }.getType());
            if (null != loginResult) {
                loginResponse = loginResult.getjData();
                if (null != loginResponse) {
                    setText(view, R.id.tv_name, loginResponse.getUserName());
                    setText(view, R.id.tv_phone, loginResponse.getPhone());

                    rb_comment.setStepSize(0.5f);
                    rb_comment.setNumStars(5);
                    rb_comment.setMax(5);
                    rb_comment.setRating(loginResponse.getScore());
                }
            }
        }
    }

    //初始化gridview
    private void initOrderView() {
        List<BaseSimpleItem> orders = mineCtrl.getOrderListBean();
        MyGridView myGridView = view.findViewById(R.id.gv_order_type);
        MineOrderAdapter mineOrderAdapter = new MineOrderAdapter(orders, R.layout.adapter_mine_order);
        mineOrderAdapter.setIngNumber(ingNumber);
        myGridView.setAdapter(mineOrderAdapter);
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), OrderListActivity.class);
                intent.putExtra("orderType", position + 1);
                startActivity(intent);
            }
        });
    }

    private int ingNumber = 0;//处理中订单的数量

    //初始化订单的数量
    private void initOrderNumber(OrderNumber orderNumber) {
        setText(view, R.id.tv_order_num_all, "" + orderNumber.getOrderAllNumber());
        setText(view, R.id.tv_order_num_success, "" + orderNumber.getOrderSuccessNumber());
        setText(view, R.id.tv_order_num_fail, "" + orderNumber.getOrderFailNumber());
        ingNumber = orderNumber.getOrderIngNumber();
        initOrderView();
    }

    //初始化listview
    private void initListView() {
        List<BaseSimpleItem> mineListBean = mineCtrl.getMineListBean(loginResponse, confing);
        MyListView myListView = view.findViewById(R.id.lv_content);
        MineAdapter mineAdapter = new MineAdapter(mineListBean, R.layout.adapter_mine);
        myListView.setAdapter(mineAdapter);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                clickListView(position);
            }
        });
    }

    //点击listview的item
    private void clickListView(int position) {
        if (position == 0) {//提现
            startActivity(new Intent(getActivity(), WithDrawActivity.class));
        } else if (position == 1) {//地址管理
            startActivity(new Intent(getActivity(), AddressListActivity.class));
        } else if (position == 2) {//常见问题
            startActivity(new Intent(getActivity(), QuestionActivity.class));
        } else if (position == 3) {//咨询客服
            UriUtils.dialPhone(confing.getPhone());
        }
    }

    @Override
    protected void praseJson(int reqId, String json) {
        if (StringUtils.isNotBlank(json)) {
            if (reqId == NetCode.ID_USERINFO) {//获取用户信息
                if (StringUtils.isNotBlank(json)) {
                    AppContext.setUserInfo(json);
                    initUserInfoView();

                    initListView();
                }
            } else if (reqId == NetCode.ID_ORDER_NUMBER) {//获取订单的数量
                OrderNumberResponse orderNumberResponse = gson.fromJson(json, new TypeToken<OrderNumberResponse>() {
                }.getType());
                if (null != orderNumberResponse) {//订单数量的接口不为空
                    initOrderNumber(orderNumberResponse.getjData());
                }
            } else if (reqId == NetCode.ID_LABEL_NUMBER) {//获取tag的数量
                MineLabelResult mineLabelResult = gson.fromJson(json, new TypeToken<MineLabelResult>() {
                }.getType());
                if (null != mineLabelResult) {
                    if (null != mineLabelResult.getjData()
                            && !ListUtils.isEmpty(mineLabelResult.getjData().getJsonArrayResult())) {
                        List<MineLabel> jsonArrayResult = mineLabelResult.getjData().getJsonArrayResult();
                        initTagView(jsonArrayResult);
                    }
                }
            }
        }

    }

    private String[] content = new String[]{"提示", "确定退出登录?", "取消", "退出"};

    //登录的操作
    private void loginOut() {
        DialogUtils.showChooseDialog(getActivity(), content, new DialogUtils.ClickRight() {
            @Override
            public void clickSure() {
                AppContext.setUserInfo("");
                AppContext.setToken("");
                AppContext.setAppKey("");
                AppContext.setAppId("");
                AppContext.setToken("");
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }

            @Override
            public void clickCancle() {

            }
        });
    }


    /****************************初始化tagview******************************/

    private void initTagView(List<MineLabel> groupTagAlls) {
        if (ListUtils.isNotEmpty(groupTagAlls)) {
            tag_view.setVisibility(View.VISIBLE);
            tv_strenth.setVisibility(View.GONE);
            tag_view.removeAllViews();
            tag_view.setGravity(Gravity.CENTER_HORIZONTAL);
            for (int i = 0; i < groupTagAlls.size(); i++) {

                final MineLabel groupTagAll = groupTagAlls.get(i);
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_tag_mine, null);
                TextView tv_label =  view.findViewById(R.id.tv_label);
                TextView tv_label_number =  view.findViewById(R.id.tv_label_number);
                tv_label.setText(groupTagAll.getLable_name());
                tv_label_number.setText("" + groupTagAll.getLabelNum());

                tag_view.addView(view);

            }
        } else {
            tag_view.setVisibility(View.GONE);
            tv_strenth.setVisibility(View.GONE);
        }
    }


    public void toggleExpand() {
        if (null != explandanableLayout) {
            explandanableLayout.clickToggleStretch();
            if (explandanableLayout.isExplandable()) {
                tv_strenth.setText("收起");
            } else {
                tv_strenth.setText("展开全部");
            }
        }
    }


    private ExplandanableLayout explandanableLayout;//
    public boolean isReDrawTag = true;//防止后面重绘myTagView的时候，再次去刷新（如果点击item中的展开tag的按钮就会去重绘）

    public void initIndicatorView() {
        tag_view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {//监听tagview绘制完成
            @Override
            public void onGlobalLayout() {
                if (isReDrawTag) {
                    tv_strenth.setText("展开全部");
                    int heightMax = tag_view.getTotalHeight();

                    int heightShrink;//
                    if (ListUtils.isNotEmpty(tag_view.getNumberHeight())) {
                        if (tag_view.getMaxLine() > 1) {
                            heightShrink = tag_view.getNumberHeight().get(1);

                            explandanableLayout = new ExplandanableLayout(tag_view, heightMax, heightShrink);
                            ViewGroup.LayoutParams layoutParams = tag_view.getLayoutParams();
                            layoutParams.height = heightShrink;
                            tag_view.setLayoutParams(layoutParams);

                            tv_strenth.setVisibility(View.VISIBLE);
                        } else {//如果行数小于2的时候，点击的indictor为不可见
                            tv_strenth.setVisibility(View.GONE);
                        }
                    } else {
                        tv_strenth.setVisibility(View.GONE);
                    }
                    isReDrawTag = false;
                }
            }
        });
    }
}
